package com.example.library_base.util

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

object TransformUtil {

    //Map转换成实体类
    fun <T> transAnyToObj(any: Any): T {
        val gson = Gson()
        val jsonString = gson.toJson(any)
        return gson.fromJson(jsonString, object: TypeToken<T>(){}.type)
    }

    //Any转换成List(返回值是LinkedTreeMap)
    fun <T> transAnyToList(any: Any): List<T> {
        val gson = Gson()
        val jsonString = gson.toJson(any)
        return gson.fromJson(jsonString, object : TypeToken<List<T>>() {}.type)
    }

    //Any转换成List
    fun <T> transAnyToList(any: Any, clazz: Class<T>): List<T> {
        val gson = Gson()
        val jsonString = gson.toJson(any)
//        val type = ParameterizedTypeImpl(clazz)
        return gson.fromJson(jsonString, object: ParameterizedType{
            override fun getActualTypeArguments(): Array<Type> {
                return arrayOf(clazz)
            }

            override fun getRawType(): Type {
                return List::class.java
            }

            override fun getOwnerType(): Type? {
                return null
            }

        })
    }

}